package cn.git.agent;

import net.bytebuddy.implementation.bind.annotation.*;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.Callable;

public class SpringMvcInterceptor {

    /**
     * 被标注 RuntimeType 注解的方法就是拦截方法，此时返回的值与返回参数可以与被拦截的方法不一致
     * byteBuddy会在运行期间给被拦截的方法参数进行赋值
     * @return
     */
    @RuntimeType
    public Object intercept(
            @This Object targetObject,
            @Origin Method targetMethod,
            @AllArguments Object[] targetMethodArgs,
            @SuperCall Callable<?> superCall) {
        Long start = System.currentTimeMillis();
        System.out.println("targetObject : " + targetObject);
        System.out.println("targetMethodName : " + targetMethod.getName());
        System.out.println("targetMethodArgs : " + Arrays.toString(targetMethodArgs));
        Object call;
        try {
            call = superCall.call();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            Long end = System.currentTimeMillis();
            System.out.println(targetMethod.getName() + "  耗时：" + (end - start) + "ms");
        }
        return call;
    }

}
